package com.example.mybatisdemo.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.example.mybatisdemo.common.Result;
import com.example.mybatisdemo.model.entity.User;
import com.example.mybatisdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author Asurf
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Resource
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登录
     */
    @PostMapping("/doLogin")
    public String doLogin(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        log.info(user.toString());
        if(username == null || password == null) {
            return "账号密码不能为空";
        }

        return userService.doLogin(username,password);
    }

    /**
     * 添加用户
     */
    @SaCheckLogin
    @ResponseBody
    @PostMapping("/add")
    public String add(@RequestBody User user) {
        if(user == null) {
            return "user为空";
        }
        return userService.insertUser(user);
    }

    /**
     * 删除用户
     */
    @SaCheckLogin
    @ResponseBody
    @PostMapping("/delete")
    public String delete(int id) {
        if(id < 0) {
            return "id不存在";
        }
        return userService.deleteUser(id);
    }

    /**
     * 修改用户信息
     */
    @SaCheckLogin
    @ResponseBody
    @PostMapping("/update")
    public String update(@RequestBody User user) {
        if(user == null) {
            return "user为空";
        }
        return userService.updateUser(user);
    }

    @SaCheckLogin
    @ResponseBody
    @PostMapping("/query")
    public Result query(int id) {
        if(id>0) {
            return Result.error("用户不存在");
        }
        return Result.success(userService.queryUser(id));
    }
}
